<template>
  <AssociateGoods
    :visible="visible"
    :formItems="formItems"
    :tableColumns="tableColumns"
    :fetchMethod="getAssociateList"
    :getAssociateKey="getAssociateKey"
    @updateVisible="updateVisible"
    @getResults="getAssociatedResults"
  />
</template>
<script>
import { mapMutations } from 'vuex';
import AssociateGoods from '../index';
import { FORM_ITEMS, TABLE_COLUMNS } from './constants/edit';
import { associatedQueryService } from '@/api/finance/salePriceManage/editSalePrice';
export default {
  components: { AssociateGoods },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    areaInfoMaps: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      formItems: FORM_ITEMS,
      tableColumns: TABLE_COLUMNS,
      getAssociateKey: row => row.id
    }
  },
  beforeDestroy () {
    this.CLEAR_ROWS()
  },
  watch: {
    areaInfoMaps () {
      this.updateFormItemsAreaInfo()
    }
  },
  methods: {
    ...mapMutations('commonComps/associateGoods', ['DELETE_ROW', 'CLEAR_ROWS']),
    // 更新开关状态
    updateVisible (state) {
      this.$emit('update:visible', state)
    },
    // 获取关联结果
    getAssociatedResults (results) {
      this.$emit('getResults', results.length == 0 ? null : results)
    },
    // 获取查询入参
    getSearchParams (infoData) {
      const { formData, paginationParams, associateState, mapValues } = infoData ?? {}
      const assIds = mapValues.map(item => this.getAssociateKey(item))
      const assFlag = associateState
      return { ...formData, ...paginationParams, assIds, assFlag }
    },
    // 获取关联商品集合
    async getAssociateList (infoData, loadingFn) {
      const data = this.getSearchParams(infoData)
      const res = await associatedQueryService(data, loadingFn)
      if (res?.retData) return res.retData
    },
    // 更新表单区域options
    updateFormItemsAreaInfo () {
      const { areaOptions, provinceOptions, cityOptions } = this.areaInfoMaps
      const optionsMaps = {
        areaCode: areaOptions,
        provinceCode: provinceOptions,
        cityCode: cityOptions
      }
      this.formItems = FORM_ITEMS.map(item => ({ ...item, options: optionsMaps[item.prop] }))
    },
    // 删除关联商品
    deleteGoods (row) {
      this.DELETE_ROW([row, this.getAssociateKey])
    }
  }
}
</script>
